package net.sourceforge.openclixml.ext;

import net.sourceforge.openclixml.EvaluationFailedException;
import net.sourceforge.openclixml.EvaluationNotSupportedException;
import net.sourceforge.openclixml.environment.IEnvironment;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import java.util.Map;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;


/**
 *
 * @version $Revision: 49 $
 * @author dominikjungo
 *
 * Last changed: $Date: 2008-04-09 22:06:24 +0200 (Wed, 09 Apr 2008) $
 * The License for this file can be found in doc/Licenses/license-OpenCliXML.txt
 */
public class LocatorType extends net.sourceforge.openclixml.autogen.LocatorType {
    /**
     * This method should not be called because a laocator cannot be evaluated.
     *
     * {@inheritDoc}
     *
     */
    @Override
    public boolean evalDelegated(
        final IEnvironment<String, String> environment,
        final Map<String, Document> systemUnderTest)
        throws EvaluationFailedException {
        throw new EvaluationNotSupportedException();
    }

    @Override
    public NodeList getFragment(
        final IEnvironment<String, String> environment,
        final Map<String, Document> systemUnderTest)
        throws XPathExpressionException {
        String expression = getXpath();
        XPath xpathE = XPathFactory.newInstance().newXPath();
        Document document = null;

        if (getAny() != null) {
            //TODO inline document testing
        } else if (getDocumentID() != null) {
            document = systemUnderTest.get(getDocumentID());
        } else if (getDocumentRef() != null) {
            //document = SUT.get(getDocumentID());
        } else {
            document = systemUnderTest.get("");
        }

        final String resolvedExpression = environment.resolveXPath(expression);
        NodeList nodesS = (NodeList) xpathE.evaluate(resolvedExpression,
                document, javax.xml.xpath.XPathConstants.NODESET);

        return nodesS;
    }
}
